import { useReducer } from "react";

// state - 上一次 state 数据
// action - 这次的 action
// function reducer(state, action) {
//   console.log("reducer", state, action);
//   return "李四";
// }

// function App() {
//   // state - 挂载阶段，有 useReducer 的第二个参数决定
//   // state - 更新阶段，由 useReducer 的第一个参数reducer的返回值决定。
//   const [state, dispatch] = useReducer(reducer, "张三");

//   console.log("state", state);
//   console.log("dispatch", dispatch);

//   return (
//     <div>
//       <h1>App - {state}</h1>
//       <button onClick={() => dispatch({ type: "change" })}>修改 state</button>
//     </div>
//   );
// }

function reducer(state, action) {
  // 根据 action.type 的不同来返回一份全新的 state 数据
  switch (action.type) {
    case "increment":
      // 返回一份全新的 state 数据
      return {
        ...state,
        count: state.count + 1,
      };
    case "decrement":
      // 返回一份全新的 state 数据
      return {
        ...state,
        count: state.count - 1,
      };
    case "change":
      return {
        ...state,
        name: action.payload,
      };
    default:
      // 原样返回上一次的state数据
      return state;
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, { count: 1, name: "张三" });

  return (
    <div>
      <h1>App</h1>
      <p>{state.count}</p>
      <p>{state.name}</p>
      <button onClick={() => dispatch({ type: "increment" })}>increment</button>
      <button onClick={() => dispatch({ type: "decrement" })}>decrement</button>
      <button onClick={() => dispatch({ type: "change", payload: "李四" })}>
        修改为李四
      </button>
      <button onClick={() => dispatch({ type: "change", payload: "王五" })}>
        修改为王五
      </button>
      <button onClick={() => dispatch({ type: "hello" })}>hello</button>
    </div>
  );
}

export default App;
